import React from 'react';
import {Calendar, DateData} from 'react-native-calendars';
import {MarkingProps} from "react-native-calendars/src/calendar/day/marking";
import {KCalendarProps} from "@/components/k-view/calendar/type";
import useTool from "@/utils";
import {useImmer} from "use-immer";
import {LocaleConfig} from 'react-native-calendars';
import {useTheme} from "@/hooks";
import languagePack from "./language";

const setLanguageConfig = (language: string) => {
    LocaleConfig.locales[language] = languagePack[language];
    LocaleConfig.defaultLocale = language;
};


const KCalendar = (props: KCalendarProps) => {
    const [{selectDateRanges}, updateState] = useImmer({
        selectDateRanges: new Array<string>(),
    });
    const {getRangeDates, sortDateArray} = useTool();

    const {colors} = useTheme();
    const {
        activeBgColor = colors.primary500,
        activeTextColor = colors.white,
        language = "zh-Hans",
        onSelect,
        ...attrs
    } = props;

    const markedDates = React.useMemo(() => {
        let dates: KCalendarProps["markedDates"] = {};
        if (selectDateRanges.length) {
            let dateList = getRangeDates(selectDateRanges)
            let length = dateList.length;
            dateList.forEach((date, index) => {
                let marked: MarkingProps = {
                    color: activeBgColor,
                    textColor: activeTextColor,
                }
                if (index == 0) marked.startingDay = true;
                if (index == length - 1) marked.endingDay = true;
                dates![date] = marked;
            });
        }
        return dates;
    }, [selectDateRanges, activeBgColor, activeTextColor]);


    const handleDayPress = (day: DateData) => {
        let index: number;
        let list = [...selectDateRanges];
        if (selectDateRanges.length >= 2) {
            list.length = 0;
            index = 0;
        } else {
            index = selectDateRanges.length;
        }
        list[index] = day.dateString;
        updateState(draft => {
            let sortList = sortDateArray(list) as string[];
            onSelect && onSelect(sortList);
            draft.selectDateRanges = sortList;
        });
    };

    setLanguageConfig(language);
    return (
        <>
            <Calendar
                theme={{
                    todayTextColor: activeBgColor,
                    dayTextColor: colors.textLight950
                }}
                enableSwipeMonths
                monthFormat={"yyyy-MM-dd"}
                markingType="period"
                {...attrs}
                markedDates={markedDates}
                onDayPress={handleDayPress}
            />
        </>
    );
};

export default KCalendar;